package com.wclass.controller.app;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wclass.common.ReturnObject;
import com.wclass.entity.BaseAppUser;
import com.wclass.entity.BaseDiscount;
import com.wclass.entity.BaseDiscountBill;
import com.wclass.entity.CourseInfo;
import com.wclass.interceptor.BaseContextHandler;
import com.wclass.service.IBaseAppUserService;
import com.wclass.service.IBaseDiscountBillService;
import com.wclass.service.IBaseDiscountService;
import com.wclass.service.ICourseInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 优惠券管理 前端控制器
 * </p>
 *
 * @author SEN
 * @since 2019-02-25
 */
@Api(description = "优惠券管理")
@RestController
@RequestMapping("/discount")
public class DiscountController {
    @Autowired
    private IBaseDiscountService iBaseDiscountService;
    @Autowired
    private IBaseDiscountBillService iBaseDiscountBillService;
    @Autowired
    private ICourseInfoService iCourseInfoService;
    @Autowired
    private IBaseAppUserService iBaseAppUserService;

    @ApiOperation("获取推广index参数")
    @RequestMapping(value = "/generalizeIndex", method = RequestMethod.POST)
    public ReturnObject generalizeIndex() {
        Map<String, Object> map = Maps.newHashMap();
        EntityWrapper<BaseDiscount> ew = new EntityWrapper<>();
        ew.eq("user_id", BaseContextHandler.getUserID()).groupBy("course_id");
        List<Integer> countList = iBaseDiscountService.selectCountByCourseId(ew);
        Integer courseCount = 0;
        for (Integer count : countList) {
            courseCount += count;
        }
        map.put("courseCount", courseCount);
        map.put("bannerCount", 0);
        return new ReturnObject(0, "添加成功", map);
    }


    @ApiOperation("老师-新增优惠券")
    @RequestMapping(value = "/addCourseDiscount", method = RequestMethod.POST)
    public ReturnObject addCouresDiscount(@ApiParam("课程ids（以，隔开）") @RequestParam String couresIds,
                                          @ApiParam("优惠券数量") @RequestParam Integer number,
                                          @ApiParam("到期时间（格式要求：yyyy-MM-dd）") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
                                          @ApiParam("到期时间（格式要求：yyyy-MM-dd）") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date expireTime,
                                          @ApiParam("优惠券金额（分为单位）") @RequestParam Long amount) {
        String[] ids = couresIds.split(",");
        for (String name : ids) {
            if (StringUtils.isNotBlank(name)) {
                iBaseDiscountService.insertInfo(Long.valueOf(name), BaseContextHandler.getUserID(), number, startTime, expireTime, amount);
            }
        }
        return new ReturnObject(0, "添加成功");
    }

    @ApiOperation("老师-优惠券分页管理")
    @RequestMapping(value = "/getTeacherDiscountPage", method = RequestMethod.POST)
    public ReturnObject getTeacherDiscountPage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                               @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                               @ApiParam("0 正在推广 1 推广过期") Integer state) {
        EntityWrapper<BaseDiscount> ew = new EntityWrapper<>();
        if (state != null) {
            ew.eq("state", state);
        }
        ew.eq("user_id", BaseContextHandler.getUserID());
        ew.orderBy("crt_time");
        Page<BaseDiscount> obj = iBaseDiscountService.selectPage(new Page<>(offset, limit), ew);
        for (BaseDiscount info : obj.getRecords()) {
            CourseInfo courseInfo = iCourseInfoService.selectById(info.getCourseId());
            info.setCouresName(courseInfo != null ? courseInfo.getName() : "");
            info.setUseedNumber(iBaseDiscountBillService.selectCount(new EntityWrapper<BaseDiscountBill>().eq("discount_id", info.getId()).eq("state", 1)));
        }
        return new ReturnObject(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

    @ApiOperation("优惠券领取情况统计-指定优惠券")
    @RequestMapping(value = "/getDiscountBillPageByDiscountId", method = RequestMethod.POST)
    public ReturnObject getDiscountBillPageByDiscountId(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                        @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                        @ApiParam("优惠券id") @RequestParam Long discountId) {
        EntityWrapper<BaseDiscountBill> ew = new EntityWrapper<>();
        ew.eq("discount_id", discountId);
        ew.orderBy("crt_time");
        Page<BaseDiscountBill> obj = iBaseDiscountBillService.selectPage(new Page<>(offset, limit), ew);
        for (BaseDiscountBill info : obj.getRecords()) {
            BaseAppUser appUser = iBaseAppUserService.selectById(info.getUserId());
            info.setUserName(appUser != null ? appUser.getUsername() : "");
        }
        return new ReturnObject(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

    @ApiOperation("学生端-获取我的优惠券分页")
    @RequestMapping(value = "/getDiscountPageByUserId", method = RequestMethod.POST)
    public ReturnObject getDiscountPageByUserId(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                @ApiParam("状态 0 未使用 1 已使用 2 已过期") @RequestParam Integer state) {
        EntityWrapper<BaseDiscountBill> ew = new EntityWrapper<>();
        ew.eq("user_id", BaseContextHandler.getUserID()).eq("state", state);
        ew.orderBy("crt_time");
        Page<BaseDiscountBill> obj = iBaseDiscountBillService.selectPage(new Page<>(offset, limit), ew);

        for (BaseDiscountBill info : obj.getRecords()) {
            BaseDiscount discount = iBaseDiscountService.selectById(info.getDiscountId());
            info.setDiscountInfo(discount != null ? discount : null);
        }
        return new ReturnObject(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

    @ApiOperation("获取指定课程-已领取的优惠券列表")
    @RequestMapping(value = "/getDiscountListByDiscountIdAndUserId", method = RequestMethod.POST)
    public ReturnObject getDiscountListByDiscountIdAndUserId(@ApiParam("课程id") @RequestParam Long courseId) {
        EntityWrapper<BaseDiscountBill> ew = new EntityWrapper<>();
        ew.eq("course_id", courseId).eq("user_id", BaseContextHandler.getUserID());
        ew.orderBy("crt_time");
        List<BaseDiscountBill> list = iBaseDiscountBillService.selectList(ew);
        List<BaseDiscount> discounts = Lists.newArrayList();
        for (BaseDiscountBill info : list) {
            BaseDiscount baseDiscount = iBaseDiscountService.selectById(info.getDiscountId());
            if (baseDiscount != null) {
                discounts.add(baseDiscount);
            }
        }
        return new ReturnObject(0, "获取成功", discounts);
    }

    @ApiOperation("领取优惠券")
    @RequestMapping(value = "/drawDiscount", method = RequestMethod.POST)
    public ReturnObject drawDiscount(@ApiParam("优惠券id") @RequestParam Long discountId) {

        List<BaseDiscountBill> list = iBaseDiscountBillService.selectList(new EntityWrapper<BaseDiscountBill>()
                .eq("discount_id", discountId).eq("user_id", BaseContextHandler.getUserID()));
        if (list.size() > 0) {
            return new ReturnObject(1, "您已领取过此优惠券");
        }
        BaseDiscount discount = iBaseDiscountService.selectById(discountId);
        if (discount == null) {
            return new ReturnObject(1, "此优惠券不存在");
        }
        if (discount.getNumber() == discount.getNumberDraw()) {
            return new ReturnObject(1, "此优惠券已被领完");
        }
        //插入优惠券记录
        iBaseDiscountBillService.insertInfo(discount, BaseContextHandler.getUserID());
        return new ReturnObject(0, "添加成功");
    }

    @ApiOperation("根据课程获取优惠券列表")
    @RequestMapping(value = "/getDiscountByCouresId", method = RequestMethod.POST)
    public ReturnObject getDiscountByCouresId(@ApiParam("优惠券id") @RequestParam Long couresIds) {
        List<BaseDiscount> list = iBaseDiscountService.selectList(new EntityWrapper<BaseDiscount>().eq("course_id", couresIds));
        return new ReturnObject(0, "获取成功", list);
    }

}

